package com.example.demo.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliBailianService {

    private static final String STATIC_URL_BASE = "http://8.154.32.215:80";
    private final String flaskBaseUrl = "http://localhost:9121/";

    public String saveFile(MultipartFile file, String path) {
        try {
            File outputFile = new File(path);
            try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                fos.write(file.getBytes());
            }
            return STATIC_URL_BASE + path.substring("/var/www/html".length());
        } catch (IOException e) {
            throw new RuntimeException("Failed to save the uploaded file.", e);
        }
    }

    public String synthesizeVoice(String fileUrl, String userInput, boolean isClone) {
        String flaskUrl = flaskBaseUrl + "voice";
        Map<String, Object> requestData = new HashMap<>();

        requestData.put("audio", fileUrl);
        requestData.put("user_input", userInput);
        requestData.put("isclone", isClone);

        return sendPostRequestToFlask(flaskUrl, requestData, "audioUrl");
    }

    public String synthesizeVideo(String imageUrl, String audioUrl) {
        String flaskUrl = flaskBaseUrl + "video";
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("image", imageUrl);
        requestData.put("audio", audioUrl);

        return sendPostRequestToFlask(flaskUrl, requestData, "videoUrl");
    }

    private String sendPostRequestToFlask(String url, Map<String, Object> requestData, String responseKey) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestData, headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        if (response.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException("Failed to call Flask API");
        }

        try {
            Map<String, Object> responseData = new ObjectMapper().readValue(response.getBody(), new TypeReference<Map<String, Object>>() {});
            System.out.println("后端返回" + responseData.get(responseKey));
            return (String) responseData.get(responseKey);

        } catch (IOException e) {
            throw new RuntimeException("Failed to parse Flask API response", e);
        }
    }
}
